package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 用来完成处理请求的环节
 */
public class DispatcherServlet {
    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getUri();
        System.out.println("请求的抽象路径:"+path);
        File file = new File("./webapps" + path);

        if(file.isFile()){//请求的是一个存在的文件
            response.setContentFile(file);
            String filename = file.getName();
            System.out.println("请求的文件名"+filename);
            /*
                1.根据文件名获取后缀名
                2.根据后缀名来设置Content-Type对应的值
             */
            int start=filename.lastIndexOf(".")+1;
            String subname =filename.substring(start);
            System.out.println("文件类型"+subname);
            Map<String,String > netkv = new HashMap<>();
            netkv.put("html","text/html");
            netkv.put("css","text/css");
            netkv.put("js","application/javascript");
            netkv.put("png","image/png");
            netkv.put("gif","image/gif");
            netkv.put("jpg","image/jpeg");
            String tetle =netkv.get(subname);
            System.out.println(tetle);

            response.addHeader("Content-Type",tetle+"");
            response.addHeader("Content-Length",file.length()+"");
        }else{
            response.setStatusCode(404);
            response.setStatusReason("Not Found");
            file = new File("./webapps/root/404.html");
            response.setContentFile(file);
            response.addHeader("Content-Type","text/html");
            response.addHeader("Content-Length",file.length()+"");
        }
        response.addHeader("Server","WebServer");
    }
}
